﻿//
//  Copyright (c) 2011 Extreme: Paweł Huryn (lead), Jakub Domański
//

using System.Configuration;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Extreme.SPFramework.Configuration
{
    /// <summary>
    /// App configuration provider
    /// </summary>
    public class AppConfigurationProvider<T> : IConfigurationSectionHandler
        where T : AppConfigurationSection
    {
        public object Create(object parent, object configContext, XmlNode section)
        {
            using (var memoryStream = new MemoryStream())
            {
                var bytes = Encoding.Default.GetBytes(section.InnerXml);
                foreach (var b in bytes)
                    memoryStream.WriteByte(b);
                memoryStream.Position = 0;

                var serializer = new XmlSerializer(typeof(T));
                Configuration = (T)serializer.Deserialize(memoryStream);
            }
            return this;
        }

        /// <summary>
        /// Configuration section
        /// </summary>
        public T Configuration
        {
            get;
            private set;
        }
    }
}
